package com.xiezc.util;

import org.junit.Test;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by xiezc on 17/2/24.
 */
public class TreadUtil {

    private static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    @Test
    public void reduce() {
        int[] arr = {4, 12, 1, 3, 5, 7, 9};
        Arrays.stream(arr).reduce((x, y) -> x + y).ifPresent(System.out::println);

        /**
         * 将reduce的第一个参数作为运算的参数
         */
        System.out.println(Arrays.stream(arr).reduce(-10, (x, y) -> {
            System.out.println(x + "  " + y);
            return x + y;
        }));

        List<Integer> list = Arrays.stream(arr).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
        System.out.println(list);
    }


    /**
     * java8的数组排序
     */
    @Test
    public void testCollectPrallel() {

        int[] data = {7, 3, 2, 1, 3, 7, 1};
        /**会对数组进行累计计算,  计算方法是传入的 函数参数;  结果是第一个本身,  第二个 为7+3, 第三个文 7+3+2  .....  */
        Arrays.parallelPrefix(data, Integer::sum);
        System.out.println(Arrays.toString(data));//[7, 10, 12, 13, 16, 23, 24]
        /** 函数 会传入一个数组的索引作为参数, 下例是对每个元素的索引(i)除以三求余数, */
        int[] data1 = {7, 3, 2, 1, 3, 7, 1};
        Arrays.parallelSetAll(data1, i -> i % 3);//[0, 1, 2, 0, 1, 2, 0]
        System.out.println(Arrays.toString(data1));
        /** 按大小排序  */
        int[] data2 = {7, 3, 2, 1, 3, 7, 1};
        Arrays.parallelSort(data2);
        System.out.println(Arrays.toString(data2));//[1, 1, 2, 3, 3, 7, 7]
    }

    @Test
    public void testLocalDate() {
        // 严格按照ISO yyyy-MM-dd验证，02写成2都不行，当然也有一个重载方法允许自己定义格式
        LocalDate date = LocalDate.parse("2016-02-05");
        System.out.println(date);

        LocalDate today = LocalDate.now();
        /** 本月的第一天 */
        LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println(firstDayOfThisMonth);

        // 取本月第2天：
        LocalDate secondDayOfThisMonth = today.withDayOfMonth(2);
        System.out.println(secondDayOfThisMonth);

        // 取本月最后一天，再也不用计算是28，29，30还是31：
        LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println(lastDayOfThisMonth);

        // 取下一天：
        LocalDate nextDay = today.plusDays(1);
        System.out.println(nextDay);
        //取下一周,  同一天, 如果今天是星期一, 则取下周的星期一的日期
        LocalDate nextweek = today.plusWeeks(1);
        System.out.println(nextweek);


        //获得2017年三月的第一个星期一, 结果是2017-03-06 ，这个计算用Calendar要死掉很多脑细胞：
        LocalDate firstMondayOf2015 = LocalDate.parse("2017-03-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
        System.out.println(firstMondayOf2015);    // 2017-03-06
    }

}
